// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import GridLineItem from "../items/GridLineItem";

const {ccclass, property} = cc._decorator;

@ccclass
export default class TrendBaseComponent extends cc.Component {

    @property(cc.Node)
    gridLayer: cc.Node = null;

    @property(cc.Prefab)
    gridLinePrefab: cc.Prefab = null;

    @property(cc.Graphics)
    averGraphic: cc.Graphics = null;

    _gridArray: any = [];

    clearGrid () {
        for (let index = 0; index < this._gridArray.length; index++) {
            let item = this._gridArray[index];
            item.node.opacity = 0;
        }
    }

    setGirdData (grids, base, rate, reverse = false) {
        this.clearGrid();
        for (let index = 0; index < grids.length; index++) {
            let value = grids[index];
            let y = reverse ? (rate * (base - value)) : (rate * (value - base)); 
            let item = this._gridArray[index];
            if (item == null) {
                let newNode = cc.instantiate(this.gridLinePrefab);
                this.gridLayer.addChild(newNode);
                item = newNode.getComponent(GridLineItem);
                this._gridArray[index] = item;
            }
            let node = item.node;
            node.opacity = 255;
            node.y = y;
            item.setItem(value + '');
        }
    }

    //渲染均线
    drawAverage (averArray, base, rate, nodeWidth) {
        this.averGraphic.clear();

        for (let index = 0; index < averArray.length; index++) {
            let calcCount = 0;
            let total = 0;
            for (let j = index; j >= 0; j--) {
                total += averArray[j];
                calcCount++;
                if (calcCount == 5) {
                    break;
                }
            }
            let averValue = total / calcCount;
            let x = nodeWidth * index + nodeWidth;
            let y = (averValue - base) * rate;
            if (index == 0) {
                this.averGraphic.moveTo(x, y);
            } else {
                this.averGraphic.lineTo(x, y);
            }
        }
        this.averGraphic.stroke();
    }

}
